<template>
  <div class="bg-white rounded-lg shadow-lg p-2">
    <!-- 本章要点介绍 -->
    <div v-if="props.showChapterHighlights" class="mb-6">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-xl font-semibold text-gray-800">本章要点介绍</h2>
        <button 
          @click="toggleChapterHighlights"
          class="flex items-center space-x-2 px-3 py-1 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded transition-colors"
        >
          <span>{{ isChapterHighlightsExpanded ? '收起' : '展开' }}</span>
          <svg 
            class="w-4 h-4 transform transition-transform duration-200" 
            :class="{ 'rotate-180': !isChapterHighlightsExpanded }"
            fill="none" 
            stroke="currentColor" 
            viewBox="0 0 24 24"
          >
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
          </svg>
        </button>
      </div>
      <div 
        class="transition-all duration-300 ease-in-out overflow-hidden"
        :class="{
          'max-h-0 opacity-0': !isChapterHighlightsExpanded,
          'max-h-screen opacity-100': isChapterHighlightsExpanded
        }"
      >
        <ChapterHighlights :chapterData="currentChapterData" />
      </div>
    </div>
    <!-- PDF显示区域 -->
    <div v-if="isPdfViewerVisible" class="border border-gray-200 rounded-lg p-2 mb-6">
      <div class="flex items-center justify-between mb-2">
        <h5 class="text-lg font-semibold text-gray-800">PDF预览</h5>
        <button @click="hidePdfViewer()" class="text-gray-500 hover:text-gray-700 text-sm font-medium">✕ 关闭</button>
      </div>
      <div class="bg-gray-50 rounded-lg p-4">
        <iframe :src="currentPdfPath" class="w-full h-[700px] border-0 rounded" title="PDF预览">
        </iframe>
      </div>
    </div>

    <!-- DOCX文档显示区域 -->
    <div v-if="isDocxViewerVisible" class="border border-gray-200 rounded-lg p-6 bg-gray-50 mb-6">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-xl font-semibold text-gray-800">文档预览</h3>
        <button @click="hideDocxViewer()" class="text-gray-500 hover:text-gray-700 text-sm font-medium">✕ 关闭</button>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoadingDocxViewer" class="flex items-center justify-center py-8">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span class="ml-3 text-gray-600">正在加载文档...</span>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="docxViewerError" class="bg-red-50 border border-red-200 rounded-lg p-4">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd"
              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
              clip-rule="evenodd" />
          </svg>
          <span class="text-red-700">{{ docxViewerError }}</span>
        </div>
      </div>

      <!-- 文档内容 -->
      <div v-else-if="docxViewerContent">
        <div class="flex gap-4" style="height: 600px;">
          <!-- 左侧目录 -->
          <div v-if="documentOutline.length > 0" :class="[
            'bg-white rounded border transition-all duration-300 ease-in-out overflow-hidden',
            isOutlineExpanded ? 'w-1/4' : 'w-12'
          ]">
            <div class="flex items-center justify-between p-4 border-b border-gray-200">
              <h4 v-if="isOutlineExpanded" class="font-semibold text-gray-700 text-sm">文档目录</h4>
              <button @click="toggleOutline" class="p-1 rounded hover:bg-gray-100 transition-colors"
                :title="isOutlineExpanded ? '收缩目录' : '展开目录'">
                <svg class="w-4 h-4 text-gray-600 transition-transform duration-200"
                  :class="{ 'rotate-180': !isOutlineExpanded }" fill="none" stroke="currentColor"
                  viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
              </button>
            </div>
            <div v-if="isOutlineExpanded" class="p-4 overflow-y-auto" style="height: calc(100% - 60px);">
              <nav class="space-y-1">
                <a v-for="(item, index) in documentOutline" :key="index" @click="scrollToHeading(item.id)" :class="[
                  'block text-sm cursor-pointer hover:text-blue-600 transition-colors py-1',
                  item.level === 1 ? 'font-medium text-gray-800' : '',
                  item.level === 2 ? 'text-gray-700 ml-4' : '',
                  item.level === 3 ? 'text-gray-600 ml-8' : '',
                  item.level === 4 ? 'text-gray-600 ml-12' : '',
                  item.level === 5 ? 'text-gray-600 ml-16' : '',
                  item.level === 6 ? 'text-gray-600 ml-20' : ''
                ]">
                  {{ item.text }}
                </a>
              </nav>
            </div>
            <div v-else class="flex flex-col items-center justify-center h-full py-4">
              <svg class="w-6 h-6 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
              </svg>
              <span class="text-xs text-gray-400 writing-mode-vertical-rl text-orientation-mixed">目录</span>
            </div>
          </div>

          <!-- 右侧文档内容 -->
          <div id="docx-viewer-content" :class="[
            'bg-white rounded border overflow-y-auto transition-all duration-300 ease-in-out',
            documentOutline.length > 0 ? (isOutlineExpanded ? 'w-3/4' : 'calc(100% - 4rem)') : 'w-full'
          ]" :style="{
            width: documentOutline.length > 0 ? (isOutlineExpanded ? '75%' : 'calc(100% - 4rem)') : '100%'
          }">
            <div class="prose max-w-none p-6" v-html="docxViewerContent"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课件资料 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <div 
        v-for="(material, index) in processedMaterials" 
        :key="index"
        class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow"
        :class="{ 'cursor-pointer': material.type === 'docx' && material.files && material.files.length > 0 }"
        @click="material.type === 'docx' && material.files && material.files.length > 0 ? showDocxViewer(material.files[0]) : null"
      >
        <div class="flex items-center mb-3">
          <svg class="w-8 h-8 mr-3" :class="getIconClass(material.icon)" fill="currentColor" viewBox="0 0 20 20">
            <path d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" />
          </svg>
          <h3 class="text-lg font-medium text-gray-800">{{ material.title }}</h3>
        </div>
        <p class="text-gray-600 text-sm mb-3">{{ material.description }}</p>
        
        <!-- 思维导图类型 -->
        <div v-if="material.type === 'mindmap'">
          <button class="w-full bg-purple-500 text-white py-2 px-4 rounded hover:bg-purple-600 transition-colors">
            预览图片
          </button>
        </div>
        
        <!-- PDF类型 -->
        <div v-else-if="material.type === 'pdf' && material.files" class="space-y-2">
          <div v-for="(file, fileIndex) in material.files" :key="fileIndex" class="flex space-x-2">
            <button @click.stop="showPdfViewer(file)"
              class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 transition-colors text-sm">
              显示
            </button>
            <button @click.stop="viewPDF(file)"
              class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 transition-colors text-sm">
              新窗口
            </button>
          </div>
        </div>
        
        <!-- DOCX类型 -->
        <div v-else-if="material.type === 'docx' && material.files" class="space-y-2">
          <div v-for="(file, fileIndex) in material.files" :key="fileIndex" class="flex space-x-2">
            <button @click.stop="showDocxViewer(file)"
              class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 transition-colors text-sm">
              显示
            </button>
            <button @click.stop="downloadDocx(file)"
              class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 transition-colors text-sm">
              下载
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import mammoth from 'mammoth'
import ChapterHighlights from './ChapterHighlights.vue'
import { useStudyTracker } from '@/composables/useStudyTracker'
import { useAuthStore } from '@/stores/auth'

// 获取学习追踪功能
const { trackMaterialClick } = useStudyTracker()

// Props定义
const props = defineProps({
  // 章节路径，用于构建材料文件路径
  chapterPath: {
    type: String,
    default: '/chap01'
  },
  // 章节编号，用于获取对应的章节数据
  chapterNumber: {
    type: Number,
    default: 1
  },
  // 材料配置
  materials: {
    type: Array,
    default: () => [
      {
        type: 'mindmap',
        title: '本章思维导图',
        description: '第1章知识点结构化思维导图',
        icon: 'purple',
        action: 'preview'
      },
      {
        type: 'pdf',
        title: '本章课件',
        description: '前端技术发展历程和基础概念介绍',
        icon: 'red',
        files: ['/第01课-绪论.pdf']
      },
      {
        type: 'docx',
        title: '本章讲义',
        description: '第1章讲义内容',
        icon: 'green',
        files: ['/第1章绪论.docx']
      }
    ]
  },
  // 是否显示章节要点
  showChapterHighlights: {
    type: Boolean,
    default: true
  }
})

// 计算属性：处理材料文件路径
const processedMaterials = computed(() => {
  return props.materials.map(material => {
    if (material.files) {
      return {
        ...material,
        files: material.files.map(file => {
          // 如果文件路径已经是完整路径（包含章节目录），直接使用
          // 否则添加chapterPath前缀
          if (file.startsWith('chap') || file.startsWith('/chap') || file.startsWith('http')) {
            return file.startsWith('/') ? file : `/${file}`
          }
          return `${props.chapterPath}${file}`
        })
      }
    }
    return material
  })
})

// PDF相关状态
const isPdfViewerVisible = ref(false)
const currentPdfPath = ref('')

// DOCX相关状态
const isDocxViewerVisible = ref(false)
const isLoadingDocxViewer = ref(false)
const docxViewerError = ref('')
const docxViewerContent = ref('')
const documentOutline = ref([])
const isOutlineExpanded = ref(true)

// 章节要点折叠状态
const isChapterHighlightsExpanded = ref(true)

// 章节要点数据状态
const chapterHighlightsData = ref(null)
const isLoadingHighlights = ref(false)
const highlightsError = ref('')

const authStore = useAuthStore()

// 获取当前章节数据
const currentChapterData = computed(() => {
  return chapterHighlightsData.value || {
    title: `第${props.chapterNumber}章 学习要点`,
    leftSection: {
      title: '暂无数据',
      icon: 'lightning',
      subsections: []
    },
    rightSection: {
      title: '暂无数据', 
      icon: 'book',
      subsections: []
    },
    tip: {
      label: '提示',
      content: '章节要点数据加载中...'
    }
  }
})

// 从API获取章节要点数据
const loadChapterHighlights = async () => {
  if (!props.chapterNumber) return
  
  isLoadingHighlights.value = true
  highlightsError.value = ''
  
  try {
    const response = await fetch(`http://localhost:806/api/chapter-highlights/chapter/${props.chapterNumber}`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.success && result.data) {
        chapterHighlightsData.value = result.data
      }
    } else if (response.status === 404) {
      // 如果没有找到对应章节的要点配置，使用默认数据
      console.log(`第${props.chapterNumber}章暂无要点配置`)
    } else {
      throw new Error('获取章节要点失败')
    }
  } catch (err) {
    console.error('加载章节要点失败:', err)
    highlightsError.value = err instanceof Error ? err.message : '加载章节要点失败'
  } finally {
    isLoadingHighlights.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadChapterHighlights()
})

// PDF相关方法
const showPdfViewer = (path) => {
  currentPdfPath.value = path
  isPdfViewerVisible.value = true
  // 记录PDF查看行为
  const fileName = path.split('/').pop() || 'PDF文件'
  trackMaterialClick(`PDF查看: ${fileName}`, path)
}

const hidePdfViewer = () => {
  isPdfViewerVisible.value = false
  currentPdfPath.value = ''
}

const viewPDF = (path) => {
  window.open(path, '_blank')
  // 记录PDF新窗口打开行为
  const fileName = path.split('/').pop() || 'PDF文件'
  trackMaterialClick(`PDF新窗口: ${fileName}`, path)
}

// DOCX相关方法
const showDocxViewer = async (path) => {
  isDocxViewerVisible.value = true
  isLoadingDocxViewer.value = true
  docxViewerError.value = ''
  
  // 记录DOCX查看行为
  const fileName = path.split('/').pop() || 'DOCX文件'
  trackMaterialClick(`DOCX查看: ${fileName}`, path)
  
  try {
    await loadDocxContent(path)
  } catch (error) {
    docxViewerError.value = `文档加载失败: ${error instanceof Error ? error.message : '未知错误'}`
    console.error('Error loading document:', error)
  } finally {
    isLoadingDocxViewer.value = false
  }
}

// 加载DOCX内容
const loadDocxContent = async (filePath) => {
  try {
    const response = await fetch(filePath)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const arrayBuffer = await response.arrayBuffer()
    
    // 使用mammoth解析DOCX文件
    const result = await mammoth.convertToHtml({ arrayBuffer })
    
    if (result.messages && result.messages.length > 0) {
      console.warn('Mammoth conversion warnings:', result.messages)
    }
    
    docxViewerContent.value = result.value
    
    // 生成文档目录
    generateDocumentOutline(result.value)
  } catch (error) {
    throw error
  }
}

// 生成文档目录
const generateDocumentOutline = (htmlContent) => {
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = htmlContent
  const headings = tempDiv.querySelectorAll('h1, h2, h3, h4, h5, h6')
  
  documentOutline.value = Array.from(headings).map((heading, index) => {
    const level = parseInt(heading.tagName.charAt(1))
    const id = `heading-${index}`
    heading.id = id
    
    return {
      id,
      text: heading.textContent || '',
      level
    }
  })
  
  // 更新文档内容以包含ID
  docxViewerContent.value = tempDiv.innerHTML
}

const hideDocxViewer = () => {
  isDocxViewerVisible.value = false
  docxViewerContent.value = ''
  documentOutline.value = []
}

const downloadDocx = (path) => {
  const link = document.createElement('a')
  link.href = path
  link.download = path.split('/').pop()
  link.click()
  
  // 记录DOCX下载行为
  const fileName = path.split('/').pop() || 'DOCX文件'
  trackMaterialClick(`DOCX下载: ${fileName}`, path)
}

const toggleOutline = () => {
  isOutlineExpanded.value = !isOutlineExpanded.value
}

const scrollToHeading = (id) => {
  const element = document.getElementById(id)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

// 切换章节要点展开/收起状态
const toggleChapterHighlights = () => {
  isChapterHighlightsExpanded.value = !isChapterHighlightsExpanded.value
}

// 获取图标样式类
const getIconClass = (iconColor) => {
  const colorMap = {
    purple: 'text-purple-500',
    red: 'text-red-500',
    green: 'text-green-500',
    blue: 'text-blue-500',
    yellow: 'text-yellow-500',
    gray: 'text-gray-500'
  }
  return colorMap[iconColor] || 'text-gray-500'
}
</script>